#include <Arduino.h>
// #include <ExpiryTimer.h>
#include "Temperature.h"
#include "AliIoTControl.h"

Temperature::Temperature(uint32_t pin_adc,
                         double bCoef,
                         double nomRes,
                         double serialRes)
    : _ntc(new NTC_Thermistor(pin_adc, nomRes, serialRes, 25, bCoef)), _last_temper(0)
{
}

Temperature::~Temperature()
{
}

bool Temperature::Run()
{
    HT_BEGIN();

    for (;;)
    {
        // _ex_timer.start(10000);
        // HT_WAIT_UNTIL(_ex_timer.expired());
        HT_DELAY(10000);

        _ftemp = _ntc.readCelsius();
        int temper = _ftemp;
        Serial.printf_P(PSTR("Temperature: %.2f°C, %.2fK, %.2f°F\n"), _ntc.readCelsius(), _ntc.readKelvin(), _ntc.readFahrenheit());

        if (temper < 0 || temper > 100)
            HT_RESTART();

        if (_last_temper != temper)
        {
            if (aliIotControl.send((char *)PSTR("currentTemperature"), temper))
            {
                _last_temper = temper;
            }
        }
    }

    HT_END();
}

float Temperature::getTemp()
{
    return _ftemp;
}
